package co.za.itweb.brainstormlite;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MenuActivity extends Activity {
	
	static String[] feeds = {
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=coverstory",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=upfront",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=indepth",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=features",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=columns",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=lastly",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=editorsnote",
		"http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=android&tag=cio"
	    
	};
	

	 static String[] feedslocal = {
			"coverstory.xml",
		    "upfront.xml",
		    "indepth.xml",
		    "features.xml",
		    "columns.xml",
		    "lastly.xml",
		    "editorsnote.xml",
		    "cio.xml"
		   
		};
	 

	 
	 protected static final String PREFS_NAME = "FAVORITES";
	 protected static final String LOGIN_NAME = "LOGIN";
	 FavoriteTask ft;
	 ArrayAdapter<String> adapter;
		static Dialog dialog;
		public static int feedValue;

		 GridAdapter favadapter;
		ArrayList<String> updated;
		
		public ProgressDialog pd;
		public static boolean firstRun;
	static Vector<RSSFeed> fList = new Vector<RSSFeed>(0);
	static Vector<RSSFeed> FavoriteList = new Vector<RSSFeed>(0);
	
	
	  @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_menu);
	        
	        if( fList.size()==0){

				
				Intent intent = new Intent(getApplicationContext(), BrainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent,2);

		    }else{
		    	populate();
		    }
	        
	       
	        
	    }
	  
	  public void populate(){

			
			ListView listView = (ListView) findViewById(R.id.mylist);
			String[] values = new String[fList.size()+1];

			for (int r = 0; r < values.length; r++) {
				if (r == 0) {
					values[r] = "Cover Story";
				}
				if (r == 1) {
					values[r] = "Upfront";
				}
				if (r == 2) {
					values[r] = "Indepth";
				}
				if (r == 3) {
					values[r] = "Features";
				}
				if (r == 4) {
					values[r] = "Columns";
				}
				if (r == 5) {
					values[r] = "Lastly";
				}
				if (r == 6) {
					values[r] = "Editor's note";
				}
				if (r == 7) {
					values[r] = "CIO Directory";
				}
				
			}

			
			
			LinearLayout layout = (LinearLayout) findViewById(R.id.cell1);//.findViewById(R.id.title)


		    int colors[] =  {Color.parseColor("#FF1f292f"),Color.parseColor("#FF1f292f")};
			GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
			layout.setBackgroundDrawable(grad);
			

	        ImageButton favorites=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.favorites);
	        ImageButton refresh=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.refresh);
	        ImageButton info=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.info);
	        

			 favorites.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog = new Dialog(MenuActivity.this);
						dialog.setContentView(R.layout.dialog_favorites);
						dialog.setTitle("Brainstorm Favorites");
						dialog.setCancelable(true);
						Button buttonclose = (Button) dialog.findViewById(R.id.closebutton);
						buttonclose.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {

								dialog.dismiss();
							}
						});
						dialog.show();
						showFavourites();
					}
				});
			 
			 refresh.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
						Intent intent = new Intent(getApplicationContext(), Refresh.class);
						startActivityForResult(intent, 1);

						
					}
				});
			 
			 
			 info.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
						Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
						startActivity(intent);
						
			
					}
				});
			 
			
			
			adapter = new ArrayAdapter<String>(this, R.layout.rowlayout,
					R.id.label, values);

			// Assign adapter to ListView
			listView.setAdapter(adapter);

			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if(position==7){
						Intent intent = new Intent(getApplicationContext(), Cio.class);
						feedValue = position;
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					}else{
					Intent intent = new Intent(getApplicationContext(), SingleFeed.class);
					feedValue = position;
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					}
					
				}
			});
			
			if(firstRun==true){
				System.out.println("RUN LATESTTTTTTTT");
				Intent intent = new Intent(getApplicationContext(), Latest.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				firstRun=false;
			}
				
	    
		}
	  
	  
	  private void showFavourites() {
			if (dialog.isShowing()) {
				String[] favorites = null;
				ListView listView2 = (ListView) dialog
						.findViewById(R.id.myfavorites);

				SharedPreferences myPrefs = getSharedPreferences(
						PREFS_NAME, MODE_WORLD_READABLE);
				String prefName = myPrefs.getString("co.za.brainstormlite.fav", "title");
				prefName = prefName.replaceAll("/", "");

				System.out
						.println("////////////////////////////////////////////////////////////////////////"
								+ prefName);
				JSONArray dat;
				try {
					dat = new JSONArray(prefName);

					favorites = new String[dat.length()];
				
					for (int t = 0; t < dat.length(); t++) {
						try {
							String obj = dat.getJSONObject(t).getString("title")
									+ "|" + dat.getJSONObject(t).getString("id")
									+ "|" + dat.getJSONObject(t).getString("feed");
							favorites[t] = obj;
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				} catch (JSONException e1) {
					e1.printStackTrace();
				}

				if (favorites != null) {
					favadapter = new GridAdapter(MenuActivity.this, favorites);
					listView2.setAdapter(favadapter);

				} else {
					Toast.makeText(getApplicationContext(), "No feeds added",
							Toast.LENGTH_SHORT).show();
					dialog.dismiss();
				}

			}

		}
	  
	  
	  public class GridAdapter extends BaseAdapter {
			String[] separated;
			private Activity activity;
			public String[] data;
			public LayoutInflater inflater = null;
			public TextView titletext;
			public ImageLoader imageLoader;
			ArrayList<String> list = new ArrayList<String>();
			JSONArray jsonArray;

			public GridAdapter(Activity a, String[] d) {
				activity = a;
				data = d;
				imageLoader = new ImageLoader(activity.getApplicationContext());
				inflater = (LayoutInflater) activity
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			}

			public int getCount() {
				return data.length;
			}

			public Object getItem(int position) {
				return position;
			}

			public long getItemId(int position) {
				return position;
			}

			public View getView(int position, View convertView, ViewGroup parent) {
				View vi = convertView;
				if (convertView == null)
					vi = inflater.inflate(R.layout.gridbanners, null);
				 separated = data[position].split("\\|");
				titletext = (TextView) vi.findViewById(R.id.texttitle);
				ImageButton erasebutton = (ImageButton) vi
						.findViewById(R.id.erasebutton);
				titletext.setText(separated[0]);
				titletext.setTag(separated[1]);
				titletext.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ft = new FavoriteTask(MenuActivity.this,v.getTag().toString());
						ft.execute();
						MenuActivity.dialog.dismiss();

					}
				});
				erasebutton.setTag(position);

				erasebutton.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						JSONArray JArray;
						try {
							SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
									MODE_WORLD_READABLE);
							String prefName = myPrefs.getString("co.za.brainstormlite.fav", "title");

							
								JArray = new JSONArray(prefName);
							
							List<Object> list = new ArrayList<Object>();
							
							for (int i=0; i<JArray.length(); i++) {
							    list.add( JArray.get(i) );
							}
							
							if(list.size()>0){
								for (int i=0; i<list.size(); i++) {
									if(Integer.parseInt(v.getTag().toString())==i  ){
										list.remove(i);
									}
								}
								    
								JSONArray jsArray = new JSONArray(list);
								
								StringBuilder buf = new StringBuilder();

								buf.append(jsArray).append("\n");

								SharedPreferences settings = getSharedPreferences(SingleNews.PREFS_NAME, 0);
								SharedPreferences.Editor editor = settings.edit();
								editor.clear();

								// SharedPreferences.Editor editor =
								// getSharedPreferences(MODE_WORLD_READABLE).edit();
								editor.putString("co.za.brainstormlite.fav", buf.toString());
								editor.commit();
								showFavourites();
								}
							
							
							
						}catch (JSONException e) {
							e.printStackTrace();
							Toast.makeText(getApplicationContext(),
									"Sorry there has been a problem with erasing your favorite news...", Toast.LENGTH_SHORT).show();
						}


					}

				});

				return vi;
			}
		}


	  @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			
			System.out.println("RESULT CODE"+resultCode +" REQUEST CODE "+requestCode+" DATA "+data);

			if (requestCode == 1) {

				if (resultCode == RESULT_OK) {
					adapter.notifyDataSetChanged();
					Toast.makeText(getApplicationContext(),
							"News are refreshed...", Toast.LENGTH_SHORT).show();
				}

				if (resultCode == RESULT_CANCELED) {
					Toast.makeText(getApplicationContext(),
							"There has been a mistake while refreshing...", Toast.LENGTH_LONG).show();
					fList.clear();
					finish();

				}
				
				
			}
				if (requestCode ==2) {
					if (resultCode == RESULT_OK) {
						firstRun=true;
						populate();

					}
				
					
					if (resultCode == RESULT_CANCELED) {
						fList.clear();
						finish();
						
						
						

					}
				}
			
		}

	  
	  private class FavoriteTask extends AsyncTask<Void, Integer ,Void>{
			RSSFeed favoriteFeed;
			ProgressDialog dialog;
			
			int id;
			public FavoriteTask(MenuActivity activity,String articleId) {
				
				this.id=Integer.parseInt(articleId.toString());
		
				dialog = new ProgressDialog(activity);
				dialog.setMessage("Loading Favorite...");
				dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				dialog.setCancelable(true);
				dialog.setMax(100);
				dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
			          public void onCancel(DialogInterface dialog) {
			        	  ft.cancel(true);
			        	  Toast.makeText(getApplicationContext(),
									"Loading canceled...", Toast.LENGTH_SHORT).show();
			          }
			    });
				dialog.show();

			}
			
			@Override
			protected Void doInBackground(Void... params) {
				FavoriteList.clear();
				
					favoriteFeed = getFeed("http://itweb.mobi/brainstorm/feed/ios-v1.php/?source=ipad&tag=article&id="+id);

					if (favoriteFeed != null) {
						FavoriteList.add(favoriteFeed);
						publishProgress();
						if (isCancelled()) {
							FavoriteList.clear();
	                        if(dialog.isShowing()){
							dialog.dismiss();
	                        }						

							return null;
						}

					

				}

				return null;
			}
			
			
			@Override
			protected void onProgressUpdate(Integer... values) {
				

			}

			@Override
			protected void onPostExecute(Void result) {
				 if(dialog.isShowing()){
						dialog.dismiss();
	                 }	
				
				
				    Intent intent = new Intent(getApplicationContext(), SingleFavorite.class);
					intent.putExtra("id", 0);
					intent.putExtra("feedid", 0);
					startActivity(intent);

			}

		

			
		
		}
	  
	  public static RSSFeed getFeed(String urlToRssFeed) {
			try {

				URL url = new URL(urlToRssFeed);

				SAXParserFactory factory = SAXParserFactory.newInstance();
				factory.setNamespaceAware(true);

				SAXParser parser = factory.newSAXParser();

				XMLReader xmlreader = parser.getXMLReader();

				RSSHandler theRssHandler = new RSSHandler();

				xmlreader.setContentHandler(theRssHandler);

				InputSource is = new InputSource(url.openStream());

				xmlreader.parse(is);

				System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
						+ theRssHandler.getFeed());
				return theRssHandler.getFeed();
			} catch (Exception ee) {
				System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
						+ ee.toString());
				return null;
			}
		}
	  
	  @Override
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
	      if (keyCode == KeyEvent.KEYCODE_BACK) {
	         SingleNews.logged=false;
	         finish();
	          return true;
	      }
	      return super.onKeyDown(keyCode, event);
	  }

}
